package name.williamwall.buxoid;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;

/**
 * This software is made available under the Gnu General Public License v3
 * and has absolutely no waranty. You may change the software to suit your needs.
 * 
 * Author: William Wall, IV
 */

public class UpdateService extends Service {
	private BuxoidDb mDb;
	private String mUser, mPass;
	private NotificationManager mNM;
	private Notification mNotification;
	private PendingIntent mContentIntent;
	
    @Override
	public void onCreate() {
		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	
	    mDb = new BuxoidDb(this);
	    mDb.open();
		
		mUser = mDb.getSetting(BuxoidDb.SETTING_USER);
		mPass = mDb.getSetting(BuxoidDb.SETTING_PASS);
		
		mContentIntent = PendingIntent.getActivity(this, 0, new Intent(this, PasswordDialog.class), 0);
		
		// show the icon in the status bar
        showNotification();
        
        Thread t = new Thread(mTask);
        t.start();
	}

    private Runnable mTask = new Runnable() {
    	public void run() {
//			Log.d("Buxfer", "Scheduled update ran");
			
			// delete old data if necessary
			mDb.deleteOldData();
			
			Buxfer b = new Buxfer(mDb);
			
			mDb.deleteOldData();
		        
		    try {
		            // login to buxfer.com api
		            mNotification.setLatestEventInfo(UpdateService.this, "Buxoid", "logging in ...", mContentIntent);
		            mNM.notify(R.string.scheduled_update_started, mNotification);
//		            Log.d(getClass().getSimpleName(), "logging in");
		            b.login(mUser, mPass);
		            
		            // upload manual transactions
		            mNotification.setLatestEventInfo(UpdateService.this, "Buxoid", "uploading transactions ...", mContentIntent);
		            mNM.notify(R.string.scheduled_update_started, mNotification);
//		            Log.d(getClass().getSimpleName(), "uploading trans");
		            b.uploadManualTransactions();
		            
		            // get accounts
		            mNotification.setLatestEventInfo(UpdateService.this, "Buxoid", "downloading accounts ...", mContentIntent);
		            mNM.notify(R.string.scheduled_update_started, mNotification);
//		            Log.d(getClass().getSimpleName(), "getting accounts");
		            b.downloadAccounts();
		            
		            // get transactions
		            mNotification.setLatestEventInfo(UpdateService.this, "Buxoid", "downloading transactions ...", mContentIntent);
		            mNM.notify(R.string.scheduled_update_started, mNotification);
//		            Log.d(getClass().getSimpleName(), "getting transactions");
		            b.downloadTransactions();
		            
		            // get analysis
		            mNotification.setLatestEventInfo(UpdateService.this, "Buxoid", "downloading analysis ...", mContentIntent);
		            mNM.notify(R.string.scheduled_update_started, mNotification);
//		            Log.d(getClass().getSimpleName(), "getting analysis");
		            b.downloadAnalysis();
		            
		            // get tags
		            mNotification.setLatestEventInfo(UpdateService.this, "Buxoid", "downloading tags ...", mContentIntent);
		            mNM.notify(R.string.scheduled_update_started, mNotification);
//		            Log.d(getClass().getSimpleName(), "getting tags");
		            b.downloadTags();
		            
		            // get impacts
		            mNotification.setLatestEventInfo(UpdateService.this, "Buxoid", "dowloading impacts ...", mContentIntent);
		            mNM.notify(R.string.scheduled_update_started, mNotification);
//		            Log.d(getClass().getSimpleName(), "getting impacts");
		            b.downloadImpacts();
		            
		            mNotification.setLatestEventInfo(UpdateService.this, "Buxoid", "update complete", mContentIntent);
		            mNM.notify(R.string.scheduled_update_started, mNotification);
		            
		            // remove notification
		            mNM.cancel(R.string.scheduled_update_started);
		    } catch (BuxException e) {
		        // you should only get a BuxException for bad User/Pass, so show a shortened message.
		        mNotification.setLatestEventInfo(UpdateService.this, "Buxoid", "Error: Incorrect user/password", mContentIntent);
                mNM.notify(R.string.scheduled_update_started, mNotification);
		    } catch (Exception e) {
		        // Send an email to the developer
		        Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
		        sendIntent.putExtra(Intent.EXTRA_TEXT, Log.getStackTraceString(e));
		        sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Buxoid Error");
		        sendIntent.setType("message/rfc822");
		        sendIntent.setData(Uri.parse("mailto:plaguester@gmail.com"));
		        
		        mContentIntent = PendingIntent.getActivity(UpdateService.this, 0, Intent.createChooser(sendIntent, "Title:"), 0);
		        
		        mNotification.setLatestEventInfo(UpdateService.this, "Buxoid", "Error occured. Click to send error report.", mContentIntent);
                mNM.notify(R.string.scheduled_update_started, mNotification);
		    }
		        
	        // close DB
	        mDb.close();
		    
	        // try to update the UI if it's there
	        try {
	            Buxoid.updateDone();
	        } catch (Exception e) {
	            // do nothing
	        } finally {
	            UpdateService.this.stopSelf();
	        }
    	}
    };
    
	@Override
	public void onDestroy() {
		// Cancel the notification -- we use the same ID that we had used to start it
//        mNM.cancel(R.string.scheduled_update_started);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}
	
	/**
     * Show a notification while this service is running.
     */
    private void showNotification() {
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.scheduled_update_started);

        // Set the icon, scrolling text and timestamp
        mNotification = new Notification(android.R.drawable.stat_notify_sync, text, System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        

        // Set the info for the views that show in the notification panel.
        mNotification.setLatestEventInfo(this, "Buxoid", "Staring update...", mContentIntent);

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mNM.notify(R.string.scheduled_update_started, mNotification);
    }

	/**
     * This is the object that receives interactions from clients.  See RemoteService
     * for a more complete example.
     */
    private final IBinder mBinder = new Binder() {
        @Override
		protected boolean onTransact(int code, Parcel data, Parcel reply,
		        int flags) throws RemoteException {
            return super.onTransact(code, data, reply, flags);
        }
    };
}
